package com.gitee.l0km.aocache.plugin;

import java.util.List;

import javax.inject.Inject;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.codehaus.mojo.aspectj.AjcTestCompileMojo;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.repository.RemoteRepository;

import static com.gitee.l0km.aocache.plugin.RelocatingSupport.addAocacheAjArtifact;
import static com.gitee.l0km.aocache.plugin.RelocatingSupport.addAocacheAjIfAbsent;
import static com.gitee.l0km.aocache.plugin.RelocatingSupport.relocateAspectjReferences;

@Mojo(name = "test-compile", threadSafe = true, defaultPhase = LifecyclePhase.TEST_COMPILE, requiresDependencyResolution = ResolutionScope.TEST)
public class AocacheTestCompileMojo extends AjcTestCompileMojo {
	@Inject
    private RepositorySystem repositorySystem;
    @Parameter(defaultValue = "${repositorySystemSession}", readonly = true)
    private RepositorySystemSession repoSession;
    
    @Parameter(defaultValue = "${project.remoteProjectRepositories}", readonly = true)
    private List<RemoteRepository> remoteRepos;
    /**
     * Whether to enable WRAP mode<br>
     * 
     * Defines the working mode during bytecode processing phase:<br>
     * WRAP mode: Inserts wrapping instructions for JoinPoint/ProceedingJoinPoint parameters in 
     * {@code INVOKEVIRTUAL} instructions that invoke aocache aspect methods across all classes.<br>
     * RELOCATE mode: Performs relocation of AspectJ reference class names in all classes: 
     * {@code org.aspectj → com.gitee.l0km.aocache.aspectj}<br>
     * Defaults to false (RELOCATE mode)
     */
    @Parameter(property = "aocache.wrapEnable", defaultValue = "false")
    private boolean wrapEnable;
	@Override
    public void execute() throws MojoExecutionException {
    	// 将构建好的模块设置为切面库数组
    	aspectLibraries = addAocacheAjIfAbsent(aspectLibraries);
        addAocacheAjArtifact(
                project,
                repositorySystem,
                repoSession,
                remoteRepos,
                getLog()
            );
        // 1. 先执行原始 AspectJ 织入逻辑
        super.execute(); 
        // 2. 在织入完成后执行引用包名替换
		relocateAspectjReferences(project.getBuild().getTestOutputDirectory(), project.getTestCompileSourceRoots(),
				getIncludedSources(), wrapEnable, getLog());
    }

}
